var dataTree = null;
$(function () {
    //加载菜单树
    $.get("../sysoffice/tree", function(r){
        dataTree = r;
        ztree = $.fn.zTree.init($("#menuTree"), setting, r.list);
        //展开所有节点
        ztree.expandAll(true);

		/*if(roleId != null){
		 vm.getRole(roleId);
		 }*/
    });

    var r = utils.getDictList("ifsuperdept,qxjb,station,setlever");
    vm.dictList1 = r.ifsuperdept;
    vm.dictList2 = r.qxjb;
    vm.dictList3 = r.station;
    vm.dictList4 = r.setlever;

    $("#jqGrid").jqGrid({

        url: '../sysoffice/getlistbydeptno',
        postData:{"id":"1"},
        datatype: "json",
        colModel: [
        { label: '用户ID', name: 'userId', index: "user_id", width: 45, key: true,hidden:true },
        { label: '手机号', name: 'mobile', width: 100 },
        { label: '用户名', name: 'username', width: 75 },
        { label: '姓名', name: 'userdesc', width: 75 },
        { label: '邮箱', name: 'email', width: 90 },
        { label: '公司', name: 'company', width: 100 },
        { label: '部门', name: 'dept', width: 100 },
        { label: '岗位', name: 'post', width: 100 ,formatter:getDictInfo},
        { label: '角色', name: 'roleName', width: 100 },
        { label: '内部数据权限', name: 'ifsuperdept', width: 150 ,formatter:getDictInfo},
        { label: '结算点级别', name: 'settlementinfo', width: 120  ,formatter:getDictInfo},
        { label: '外部数据权限', name: 'settlementleverName', width: 180 },
        { label: '外部数据权限', name: 'settlementlever', width: 100,hidden:true },


        { label: '是否主管', name: 'issupervisor', width: 80 ,
            formatter:function(v){
                if(v=="0"){
                    return "是";
                }else  if(v=="1"){
                    return "否"
                }else {
                    return "";
                }
            } },
        { label: '状态', name: 'status', width: 80, formatter: function(value, options, row){
            return value === 0 ?
                '<span class="label label-danger">禁用</span>' :
                '<span class="label label-success">正常</span>';
        }},
        { label: '创建时间', name: 'createTime', index: "create_time",  width: 86, formatter:"date", formatoptions: {newformat:'Y-m-d'}
        }
    ],
        viewrecords: true,
        height: 360,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        shrinkToFit:false,
        autoScroll: false,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
           // $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
        /*url: '../sysoffice/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true, key:true, hidden:true },
			{ label: '父级编号', name: 'parentId', index: 'parent_id', width: 80, hidden:true },
			{ label: '名称', name: 'name', index: 'name' },
			{ label: '排序', name: 'sort', index: 'sort', hidden:true },
			{ label: '归属区域', name: 'areaId', index: 'area_id',hidden:true },
			{ label: '区域编码', name: 'code', index: 'code', hidden:true },
			{ label: '机构类型', name: 'type', index: 'type', hidden:true },
			{ label: '机构等级', name: 'grade', index: 'grade', hidden:true },
			{ label: '联系地址', name: 'address', index: 'address', width: 80 }, 			
			{ label: '邮政编码', name: 'zipCode', index: 'zip_code', hidden:true },
			{ label: '负责人', name: 'master', index: 'master', hidden:true},
			{ label: '电话', name: 'phone', index: 'phone', width: 80 }, 			
			{ label: '传真', name: 'fax', index: 'fax', width: 80 }, 			
			{ label: '邮箱', name: 'email', index: 'email', width: 80 },
            { label: '是否公司', name: 'isConmpany', index: 'isConmpany', hidden:true },
            { label: '是否启用', name: 'useable', index: 'USEABLE', hidden:true },
			{ label: '主负责人', name: 'primaryPerson', index: 'PRIMARY_PERSON', hidden:true },
			{ label: '副负责人', name: 'deputyPerson', index: 'DEPUTY_PERSON', hidden:true },
			{ label: '创建者', name: 'createBy', index: 'create_by', hidden:true },
			{ label: '创建时间', name: 'createDate', index: 'create_date', hidden:true },
			{ label: '更新者', name: 'updateBy', index: 'update_by', hidden:true },
			{ label: '更新时间', name: 'updateDate', index: 'update_date', hidden:true },
			{ label: '备注信息', name: 'remarks', index: 'remarks', hidden:true },
			{ label: '删除标记', name: 'delFlag', index: 'del_flag', hidden:true }
        ],
		viewrecords: false,
        treeGrid: true,
		// height: $(window).height()*0.5,
        // datatype
        treedatatype:"json",
        // the model used
        treeGridModel:"adjacency",//nested
        ExpandColumn : 'name',
        scroll: "true",
		loadonce: true,
		width:"auto",
        //height: 385,
        rowNum: 100,
		//rowList : [10,30,50],
        //rownumbers: true,
        //rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        treeReader:{
            level_field: "level",
            parent_id_field: "parentId", // then why does your table use "parent_id"?
            leaf_field: "isleaf",
            loaded:"loaded",
            expanded_field: "expanded",
            icon_field:"icon"
        },
       prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        height: "auto",    // 设为具体数值则会根据实际记录数出现垂直滚动条
        //rowNum : "-1",     // 显示全部记录
		sortable:true,
        sortorder:"desc",*/
    });
});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: "id"
        },
        key: {
            url:"nourl"
        }
    },
    check:{
        enable:false,  //是否复选，默认true
        nocheckInherit:true
    },

    async : { // 是否异步加载 相当于ajax
      /*  autoParam : [], //可以设置提交时的参数名称，例如 server 只接受 zId : ["id=zId"] ; 默认值空
        contentType : "application...",
        dataFilter : null,
        dataType : "text",*/
        url:"../sysoffice/tree",
        enable : true,//设置 zTree 是否开启异步加载模式
         },
    callback:{
        beforeClick: getCurrentNode
        //onClick : zTreeOnClick
    }
};

function getCurrentNode(treeId, treeNode){
	vm.parentId=treeNode.id;
    curNode = treeNode;
    zTreeOnClick(curNode);
	/*beforeClick: function(treeId, treeNode) {
	 var zTree = $.fn.zTree.getZTreeObj("#menuTree");
	 if (treeNode.isParent) {
	 zTree.expandNode(treeNode);
	 return false;
	 } else {
	 demoIframe.attr("src",treeNode.file + ".html");
	 return true;
	 }
	 }*/
};
function zTreeOnClick(treeNode){
    //alert(treeNode.name);
    vm.showList = true;
    vm.unitId = treeNode.unitId;
    var page = $("#jqGrid").jqGrid('getGridParam','page');
    $("#jqGrid").jqGrid('setGridParam',{
        postData:{'id': treeNode.id},
        page:page
    }).trigger("reloadGrid");
};
var ztree;

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
        showtable:false,
		title: null,
        parentId:"",
		sysOffice: {},

        roleList:{},
        user:{
            status:1,
            roleIdList:[],
            name:""
        },
        dictList1:{},
        dictList2:{},
        dictList3:{},
        dictList4:{},
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			/*if(vm.parentId==null||vm.parentId==''){
				alert("请选择组织架构树再新增");
				return;

			}*/
			vm.showList = false;
            vm.showtable = false;
			vm.title = "新增";
			vm.sysOffice = {
                parentId:vm.parentId,
                useable:'Y',
			};
		},
		update: function (event) {
            if(vm.parentId==null||vm.parentId==''){
             alert("请选择组织架构树再修改");
             return;
             }
			/*var id = vm.getSingleRow();
			if(id == null){
				return ;
			}*/
			vm.showList = false;
            vm.showtable = false;
            vm.title = "修改";

            vm.getInfo(vm.parentId)
		},
        saveOrUpdate: function (event) {
			var url = vm.sysOffice.id == null ? "../sysoffice/save" : "../sysoffice/update";
			$.ajax({
				type: "POST",
			    url: url,
			    contentType: "application/json",
			    data: JSON.stringify(vm.sysOffice),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
                            vm.refreshNode();
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
            if(vm.parentId==null||vm.parentId==''){
                alert("请选择组织架构树再修改");
                return;
            }
            var zTree = $.fn.zTree.getZTreeObj("menuTree");
            nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            if(node.isParent){
                alert("该节点下有组织架构，不能删除");
                return;
            }
            var total = $("#jqGrid").jqGrid('getGridParam', 'records'); //获取查询得到的总记录数量

            // var obj = $("#jqGrid").jqGrid("getRowData");
            if(total>0){
                alert("该节点下有员工，不能删除");
                return;
            }

			/*var ids = vm.getSingleRow();
			if(ids == null){
				return ;
			}*/
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: "../sysoffice/delete",
				    contentType: "application/json",
				    data: JSON.stringify(vm.parentId),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
                                vm.refreshNode();
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
        refreshNode:function() {
        /*根据 treeId 获取 zTree 对象*/
            // var zTree = $.fn.zTree.getZTreeObj("menuTree");
            // zTree.reAsyncChildNodes(null, "refresh");
            $.get("../sysoffice/tree", function(r){
                dataTree = r;
                ztree = $.fn.zTree.init($("#menuTree"), setting, r.list);
                //展开所有节点
                ztree.expandAll(true);

                /*if(roleId != null){
                 vm.getRole(roleId);
                 }*/
            });
         /*   type = "refresh";
            silent = false;
            /!*获取 zTree 当前被选中的节点数据集合*!/
             nodes = zTree.getSelectedNodes();
        /!*强行异步加载父节点的子节点。[setting.async.enable = true 时有效]*!/
         zTree.reAsyncChildNodes(nodes[0], type, silent);*/
    },
getInfo: function(id){
			$.get("../sysoffice/info/"+id, function(r){
                vm.sysOffice = r.sysOffice;
            });
		},
		reload: function (event) {
			vm.showList = true;
            vm.showtable = false;
            vm.parentId="";
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
				postData:{"time":new Date().getTime()},
                page:page
            }).trigger("reloadGrid");
		},
		getSingleRow: function(){
            var grid = $("#jqGrid");
            var rowKey = grid.getGridParam("selrow");
            if(!rowKey){
                alert("请选择一条记录");
                return ;
            }
            return rowKey;
		},

        closePop:function(){

            document.getElementById("leftDiv").className="col-sm-8";
            document.getElementById("rigthMune").style.display ="block";
            $("#pop").animate({left:'-3500px'});
        },

        selectDept: function(){
            popPage.popOfficeGrid();
            // var page = $("#popOfficeGrid").jqGrid('getGridParam','page');
            // $("#popOfficeGrid").trigger("reloadGrid");
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择部门",
                area: ['370px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#popOffice"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#popOfficeGrid");
                    var rowKey = grid.getGridParam("selrow");
                    if(!rowKey){
                        alert("请选择一条记录");
                        return ;
                    }

                    var rowData=grid.jqGrid("getRowData",rowKey);

                    var id=rowData.id;
                    vm.sysOffice.parentId=id;


                    layer.close(index);
                }
            });
        },


      /*  员工账号应用*/

        addAccount: function(){
            vm.showList = false;
            vm.showtable=true;
            vm.title = "新增";
            vm.roleList = {};
            vm.user = {issupervisor:"1",status:1,roleIdList:[],dept:"",roleName:"",settlementlever:"",settlementleverName:""};
            $('#dept').attr("disabled", false);
            $('#post').attr("disabled", false);
            //获取角色信息
            this.getRoleList();
        },
        updateAccount: function () {
            var userId = getSelectedRow();
            if(userId == null){
                return ;
            }
            $('#dept').attr("disabled", true);
            $('#post').attr("disabled", true);

            var obj = $("#jqGrid").jqGrid("getRowData");
            vm.showtable=true;
            vm.showList = false;
            vm.title = "修改";

            vm.getUser(userId);
            //获取角色信息
            this.getRoleList();
        },
        delAccount: function () {
            var userIds = getSelectedRows();
            if(userIds == null){
                return ;
            }

            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: "../sys/user/delete",
                    contentType: "application/json",
                    data: JSON.stringify(userIds),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },

        saveOrUpdateAccount: function (event) {
            var url = vm.user.userId == null ? "../sys/user/save" : "../sys/user/update";
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.user),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },

        getUser: function(userId){
            $.get("../sys/user/info/"+userId, function(r){
                vm.user = r.user;
            });
        },
        getRoleList: function(){
            $.get("../sys/role/select", function(r){
                vm.roleList = r.list;
            });
        },

        /*reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'username': vm.q.username},
                page:page
            }).trigger("reloadGrid");
        },*/
        selectDept2: function(){
            $("#popOfficeGrid1").jqGrid({
                url: '../sysoffice/selectDept',
                datatype: "json",
                colModel: [
                    { label: 'id', name: 'id', index: "id", width: 45, key: true,hidden:true },
                    { label: 'parentId', name: 'parentId', index: "parent_id", width: 45,hidden:true },

                    { label: '名称', name: 'name', index: "name", width: 250 },
                ],
                viewrecords: true,
                height: 260,
                rowNum: 10000,
                rowList : [10,30,50],
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect:false,
                 // pager: "#popOfficeGridPager1",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#popOfficeGrid1").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });
            var page = $("#popOfficeGrid1").jqGrid('getGridParam','page');
            $("#popOfficeGrid1").jqGrid('setGridParam',{
                page:page
            }).trigger("reloadGrid");
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择部门",
                area: ['330px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#popOffice1"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#popOfficeGrid1");
                    var rowKey = grid.getGridParam("selrow");
                    if(!rowKey){
                        alert("请选择一条记录");
                        return ;
                    }

                    var rowData=grid.jqGrid("getRowData",rowKey);
                    /*  if(rowData.isConmpany=='Y'){
                     alert("不能选择公司，请选择部门");
                     return ;
                     }*/
                    vm.user.dept = rowData.name;
                    vm.user.deptNo = rowData.id;
                    var id=rowData.parentId;
                    vm.user.companyid=id;

                    $.get("../sysoffice/info/"+id, function(r){
                        vm.user.company=r.sysOffice.name;;
                    });
                    layer.close(index);
                }
            });
        },

        selectRole: function(){
            popPage.popRoleGrid();
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择角色",
                area: ['540px', '350px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#popRole"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#popRoleGrid");
                    var rowKey = grid.getGridParam("selrow");
                    if(!rowKey){
                        alert("请选择一条记录");
                        return ;
                    }

                    var ids= grid.getGridParam("selarrrow");

                    var len = ids.length;
                    var roleNames;
                    var roleIds;
                    vm.user.roleIdList=[];
                    for(var i = 0;i < len ;i ++) {
                        var rowData=grid.jqGrid("getRowData",ids[i]);
                        vm.user.roleIdList.push(rowData.roleId);
                        if(i==0){
                            roleNames=rowData.roleName;
                            roleIds=rowData.roleId;

                        }else{
                            roleNames+=","+rowData.roleName;
                            roleIds+=","+rowData.roleId;
                        }

                    }
                    vm.user.roleName=roleNames;
                    vm.user.roleId=roleIds;

                    /*  var grid = $("#popRoleGrid");
                     var rowKey = grid.getGridParam("selrow");
                     if(!rowKey){
                     alert("请选择一条记录");
                     return ;
                     }
                     var rowData=grid.jqGrid("getRowData",rowKey);*/


                    layer.close(index);
                }
            });
        },

        selectunit: function () {
            var settlementinfo = vm.user.settlementinfo;
            console.log(settlementinfo);
            if (settlementinfo == "qxjb01") {//责任区域
                this.responseArea();
            } else if (settlementinfo == 'qxjb02' ) {//责任部门
                this.selectDept1();
            } else if (settlementinfo == 'qxjb03') {//责任人
                this.popUser();
            } else {
                alert("请选择结算点级别名称！");
                return;
            }
        },

        selectDept1: function(){
            popPage.popDeptGrid('','','Y');

            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择部门",
                area: ['290px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#windowunit"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#jqGridselect");
                    var rowKey = grid.getGridParam("selrow");
                    if(!rowKey){
                        alert("请选择一条记录");
                        return ;
                    }
                    var ids= grid.getGridParam("selarrrow");
                    var len = ids.length;
                    var names;
                    var idss;
                    for(var i = 0;i < len ;i ++) {
                        var rowData=grid.jqGrid("getRowData",ids[i]);
                        if(i==0){
                            names=rowData.name;
                            idss= rowData.id;
                        }else{
                            names+=","+rowData.name;
                            idss+=","+rowData.id;

                        }

                    }
                    vm.user.settlementleverName=names;
                    vm.user.settlementlever=idss;


                    layer.close(index);
                }
            });
        },

        popUser: function(){
            popPage.popUserGrid('','',true);
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择人",
                area: ['750px', '400px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#popUser"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#popUserGrid");
                    var rowKey = grid.getGridParam("selrow");
                    if(!rowKey){
                        alert("请选择一条记录");
                        return ;
                    }
                    var ids= grid.getGridParam("selarrrow");
                    var len = ids.length;
                    var userIds;
                    var names;
                    for(var i = 0;i < len ;i ++) {
                        var rowData=grid.jqGrid("getRowData",ids[i]);
                        if(i==0){
                            userIds=rowData.userId;
                            names=rowData.userdesc;
                        }else{
                            userIds+=","+rowData.userId;
                            names+=","+rowData.userdesc;
                        }

                    }
                    vm.user.settlementlever=userIds;
                    vm.user.settlementleverName=names;

                    layer.close(index);
                }
            });
        },


        responseArea: function(){
            $("#jqGridselect1").jqGrid({
                url: '../sysdict/list',
                datatype: "json",
                postData: {"type":"setlever"},
                colModel: [
                    { label: 'ID', name: 'id', index: "id", width: 45, key: true },
                    { label: '名称', name: 'label', index: "label", width: 200 },
                    { label: '值', name: 'value', index: "value",hidden:true},

                ],
                viewrecords: true,
                height: 200,
                rowNum: 1000,
                /*   rowList : [10,30,50],*/
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,
                // shrinkToFit:false,
                autoScroll: false,
                //pager: "#popOfficeGridPager",
                jsonReader : {
                    root: "page.list",
                    /* page: "page.currPage",
                     total: "page.totalPage",
                     records: "page.totalCount"*/
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#jqGridselect1").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });

        /*    $("#jqGridselect1").jqGrid("clearGridData");
            $("#jqGridselect1").jqGrid('getGridParam','page');
            $("#jqGridselect1").jqGrid('setGridParam',{
                url: '../sysdict/list',
                datatype: "json",
                postData: {"type":"setlever"},
            }).trigger("reloadGrid");*/

            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择区域",
                area: ['330px', '340px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#windowunit1"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#jqGridselect1");
                    var rowKey = grid.getGridParam("selrow");
                    if(!rowKey){
                        alert("请选择一条记录");
                        return ;
                    }

                    var ids= grid.getGridParam("selarrrow");
                    var len = ids.length;
                    var values;
                    var names;
                    for(var i = 0;i < len ;i ++) {
                        var rowData=grid.jqGrid("getRowData",ids[i]);
                        if(i==0){
                            values=rowData.value;
                            names=rowData.label;
                        }else{
                            values+=","+rowData.value;
                            names+=","+rowData.label;

                        }

                    }
                    vm.user.settlementlever=values;
                    vm.user.settlementleverName=names;


                    layer.close(index);
                }
            });
        },



    }
});


function infoChange(){
    vm.user.settlementleverName="";
    vm.user.settlementlever="";
}
